package org.jradweb.core.taglib;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
/**
 * e.g. Tag <b>&lt;j:href controller="user" value="list"/&gt;</b> will print "contextPath/user/list.html" to page.
 * <br/>
 * <br/>Created On Apr 21, 2008
 * @author <a href="mailto:wagzhi@gmail.com">Paul Wang</a>
 * @version $Id: HrefTag.java 149 2008-10-10 03:10:10Z wagzhi $
 */
public class HrefTag extends BaseTag {

	private String filenameExtension;
	private String controller;
	private String action;
	private Object oid;

	public Object getOid() {
		return oid;
	}

	public void setOid(Object oid) {
		this.oid = oid;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public String getController() {
		return controller;
	}

	public void setController(String controller) {
		this.controller = controller;
	}

	@Override
	public int doEndTag() throws JspException {
		HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
		String contextPath = req.getContextPath();
		String url = this.getUrl(contextPath, controller, action, oid);
		try {
			this.pageContext.getOut().write(url);
		} catch (IOException e) {
			throw new JspException(e);
		}
		return super.doEndTag();

	}

	private String getUrl(String contextPath, String controller, String action,
			Object oid) {
		StringBuffer sb = new StringBuffer(contextPath).append("/");
		if (controller != null) {
			sb.append(controller.toLowerCase());
			if (action != null) {
				sb.append("/").append(action.toLowerCase()).append(".html");
			} else {
				sb.append("/index.html");
			}

			if (oid != null)
				sb.append("?id=").append(oid.toString());
		}

		return sb.toString();
	}

	public String getFilenameExtension() {
		return filenameExtension;
	}

	public void setFilenameExtension(String filenameExtension) {
		this.filenameExtension = filenameExtension;
	}

}
